import React, { useEffect } from 'react'
import { DownOutlined, UserOutlined } from '@ant-design/icons'
import { Link, history, useModel } from 'umi'
import { Avatar, Dropdown, Menu, Space } from 'antd'
import { MenuClickEventHandler } from 'rc-menu/lib/interface'
import FullScreen from '@/components/FullScreen'
import { Gitee, LoginPath, ProjectTitle } from '@/common/constants'
import Setting from './setting'

const HeaderHelper = () => {
  const { initialState, setInitialState } = useModel('@@initialState')
  const { StorgeSet, StorgeGet } = useModel('storge')
  const { nickname, avatar } = StorgeGet({ path: 'info' })

  useEffect(() => {
    if (!nickname) {
      toLogin()
    }
  }, [nickname])

  const toLogin = () => {
    setInitialState({ ...initialState, currentUser: undefined })
    StorgeSet({ path: 'info', value: {} })
    sessionStorage.removeItem(`${ProjectTitle}-username`)

    setTimeout(() => {
      history.push(LoginPath)
    }, 500)
  }

  const onDropMenu: MenuClickEventHandler = (info) => {
    if (info.key === 'logout') {
      toLogin()
    }
  }

  const dropMenu = (
    <Menu className="app-overlay-menu" onClick={onDropMenu}>
      <Menu.Item key="dashboard">
        <Link to="/dashboard">首页</Link>
      </Menu.Item>
      <Menu.Item key="project">
        <a target="_blank" href={Gitee} rel="noopener noreferrer">
          项目地址
        </a>
      </Menu.Item>
      <Menu.Divider />
      <Menu.Item key="logout">退出登录</Menu.Item>
    </Menu>
  )

  return (
    <div className="app-helper-menu">
      <Setting />
      <FullScreen />
      <div className="header-dropdown-wrap">
        <Dropdown
          overlayClassName="app-header-down"
          arrow
          overlay={dropMenu}
          overlayStyle={{ right: '-30px', left: 0 }}
        >
          <Space>
            <Avatar shape="square" size="small" src={avatar} icon={<UserOutlined />} />
            {nickname}
            <DownOutlined />
          </Space>
        </Dropdown>
      </div>
    </div>
  )
}

export default HeaderHelper
